package net.oschina.simpleplus;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import net.oschina.simpleplus.demo.protobuf.model.HelloRequest;
import net.oschina.simpleplus.demo.protobuf.model.HelloResponse;
import net.oschina.simpleplus.demo.protobuf.serv.HelloServiceGrpc;
import net.oschina.simpleplus.servreg.ZooKeeperServReg;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;


public class HelloClient {
	private static final Logger logger = LoggerFactory.getLogger(HelloClient.class);

	private final ManagedChannel channel;
	private HelloServiceGrpc.HelloServiceBlockingStub blockingStub;

	public HelloClient(String host, int port) {
		this(ManagedChannelBuilder.forAddress(host, port).usePlaintext(true));
	}

	HelloClient(ManagedChannelBuilder channelBuilder) {
		channel = channelBuilder.build();
		blockingStub = HelloServiceGrpc.newBlockingStub(channel);
	}

	public void shutdown() throws InterruptedException {
		channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
	}

	/** Say hello to server. */
	public void sayHello(String name) {
		logger.info("Will try to sayHello {} .....", name);
		HelloRequest request = HelloRequest.newBuilder().setName(name).build();
		HelloResponse response;
		try {
			response = blockingStub.sayHello(request);
		} catch (StatusRuntimeException e) {
			logger.error("RPC failed: {}", e.getStatus(), e);
			return;
		}
		logger.info("recv msg: {}", response.getMessage());
	}

	public static void main( String[] args ) {
		HelloClient helloClient = null;
		try {
			ZooKeeperServReg zk = new ZooKeeperServReg();
			zk.connect("localhost:2181");
			String path = "/grpc/serverList";
			
			List<String> children = zk.getChildren(path);
			if(children.isEmpty()){
				int count = 1;
				logger.info("path:{} has not childNode", path);
				while(children.isEmpty()){
					TimeUnit.SECONDS.sleep(3);
					children = zk.getChildren(path);
					count++;
					
					if(children.isEmpty() && count > 10){
						logger.info("has done {} tries get path:{} has not childNode", count, path);
						System.exit(0);
						break;
					}
				}
			}
			
			String string = children.get(0);
			logger.info("path: {}, {}", path, string);
			String[] split = string.split(":");
			helloClient = new HelloClient(split[0], Integer.parseInt(split[1]));
			helloClient.sayHello("world");
		} catch (IOException | InterruptedException | KeeperException e) {
			logger.error("", e);
		} finally {
			if(helloClient !=  null)
				try {
					helloClient.shutdown();
					
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
			
		}
		
		
		

    }
}
